//
//  NetworkTools.swift
//  封装AFN(sft)
//
//  Created by teacher on 16/4/17.
//  Copyright © 2016年 teacher. All rights reserved.
//

import UIKit
import AFNetworking

// 请求方式
enum HMRequestMethod: String {
    case Post = "post"
    case Get = "get"
}


class NetworkTools: AFHTTPSessionManager {
    
    // 单例：全局访问点
    static let sharedTools: NetworkTools = {
        let tools = NetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
         tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    // 定义请求
    typealias HMRequestCallBack = (responseObject: AnyObject?, error: NSError?)->()
    
    
    // 如果以后在公司开发过程中，某种类型的请求方式使用的频率比较高，那么可以给请求参数添加一个默认值
    /// 发送请求数据
    ///
    /// - parameter method:     请求方式
    /// - parameter urlString:  请求地址
    /// - parameter parameters: 请求参数
    /// - parameter finished:   请求完成之后的回调
    func request(method: HMRequestMethod = .Post, urlString: String, parameters: AnyObject?, finished: HMRequestCallBack){
        
        // 定义一个请求成功之后要执行的闭包
        let success = { (dataTask: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
            // 请求成功的回调
            finished(responseObject: responseObject, error: nil)
        }
        
        // 定义一个请求失败之后要执行的闭包
        let failure = { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
            finished(responseObject: nil, error: error)
        }
        
        if method == .Get {
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
    
    // 提供给外界一个请求数据的方法
    
    // 请求类型，请求地址，请求参数，请求完成之后的回调
//    func request(method: HMRequestMethod, urlString: String, parameters: AnyObject?, finished: (responseObject: AnyObject?, error: NSError?)->()){
//        
//        if method == .Get {
//            GET(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) -> Void in
//                // 请求成功的回调
//                finished(responseObject: responseObject, error: nil)
//            }, failure: { (_, error) -> Void in
//                finished(responseObject: nil, error: error)
//            })
//        }else{
//            POST(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) -> Void in
//                // 请求成功的回调
//                finished(responseObject: responseObject, error: nil)
//            }, failure: { (_, error) -> Void in
//                    finished(responseObject: nil, error: error)
//            })
//        }
//    }
}
